package cn.itcast.web.controller.cargo;

import cn.itcast.domain.cargo.*;
import cn.itcast.service.cargo.ExportService;
import cn.itcast.service.cargo.InvoiceService;
import cn.itcast.service.cargo.PackingService;
import cn.itcast.service.cargo.ShippingService;
import cn.itcast.vo.ShippingOrder;
import cn.itcast.web.controller.BaseController;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import cn.itcast.service.cargo.PackingService;
import cn.itcast.service.cargo.ShippingService;
import cn.itcast.web.controller.BaseController;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.SimpleFormatter;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/cargo/shipping")
public class ShippingController extends BaseController {

    @Reference
    private PackingService packingService;

    @Reference
    private ExportService exportService;

    @Reference
    private ShippingService shippingService;

    @Reference
    private InvoiceService invoiceService;

    /**
     * 1. 委托管理列表
     */
    @RequestMapping("/list")
    public String contractList(@RequestParam(defaultValue = "1") Integer pageNum,
                               @RequestParam(defaultValue = "5") Integer pageSize) {

        ShippingExample shippingExample = new ShippingExample();
        shippingExample.createCriteria().andCompanyIdEqualTo(getLoginCompanyId());
        shippingExample.setOrderByClause("create_time desc");
        PageInfo<Shipping> pageInfo = shippingService.findByPage(shippingExample, pageNum, pageSize);
        request.setAttribute("pageInfo", pageInfo);
        return "cargo/shipping/shipping-list";
    }

    @RequestMapping("/save")
    public String save(Shipping shipping) {
        shipping.setCompanyId(getLoginCompanyId());
        shipping.setCompanyName(getLoginCompanyName());
        shipping.setCreateBy(getLoginUser().getId());
        shipping.setCreateDept(getLoginUser().getDeptId());
        shipping.setCreateTime(new Date());
        shippingService.save(shipping);
        return "redirect:/cargo/shipping/list";
    }

    @RequestMapping("/delete")
    @ResponseBody
    public Map<String, Object> delete(String id) {
        return shippingService.delete(id);
    }

    /*location.href="${ctx}/cargo/shipping/toExcel.do?id="+id;*/
    @RequestMapping("/toExcel")
    @ResponseBody
    public void toExcel(String id) throws Exception {
        ShippingOrder shippingOrder = getShippingOrder(id);
        InputStream in = session.getServletContext().getResourceAsStream("/make/xlsprint/shippingOrder.xlsx");
        Workbook workbook = new XSSFWorkbook(in);
        Sheet sheet = workbook.getSheetAt(0);

        Row row = sheet.getRow(3);
        Cell cell = row.getCell(0);
        cell.setCellValue(shippingOrder.getShipper());
        row = sheet.getRow(8);
        cell = row.getCell(0);
        cell.setCellValue(shippingOrder.getConsignee());
        row = sheet.getRow(15);
        cell = row.getCell(0);
        cell.setCellValue(shippingOrder.getNotifyPariy());

        row = sheet.getRow(19);
        cell = row.createCell(0);
        cell.setCellValue(shippingOrder.getInvoiceId());
        cell.setCellStyle(sheet.getRow(18).getCell(0).getCellStyle());
        cell = row.createCell(3);
        cell.setCellValue(shippingOrder.getInvoiceTime());
        cell.setCellStyle(sheet.getRow(18).getCell(3).getCellStyle());
        cell = row.createCell(6);
        cell.setCellValue(shippingOrder.getLcNO());
        cell.setCellStyle(sheet.getRow(18).getCell(6).getCellStyle());
        row = sheet.getRow(23);
        cell = row.createCell(0);
        cell.setCellValue(shippingOrder.getPortOfLoading());
        cell.setCellStyle(sheet.getRow(22).getCell(0).getCellStyle());
        cell = row.createCell(3);
        cell.setCellValue(shippingOrder.getPortOfTrans());
        cell.setCellStyle(sheet.getRow(22).getCell(3).getCellStyle());
        cell = row.createCell(6);
        cell.setCellValue(shippingOrder.getPortOfDischar());
        cell.setCellStyle(sheet.getRow(22).getCell(6).getCellStyle());

        row = sheet.getRow(27);
        cell = row.createCell(0);
        cell.setCellValue(shippingOrder.getLoadingDate());
        cell.setCellStyle(sheet.getRow(26).getCell(0).getCellStyle());
        cell = row.createCell(2);
        cell.setCellValue(shippingOrder.getLimitDate());
        cell.setCellStyle(sheet.getRow(26).getCell(2).getCellStyle());
        cell = row.createCell(3);
        cell.setCellValue(shippingOrder.getIsBatch());
        cell.setCellStyle(sheet.getRow(26).getCell(3).getCellStyle());
        cell = row.createCell(5);
        cell.setCellValue(shippingOrder.getIsTrans());
        cell.setCellStyle(sheet.getRow(26).getCell(5).getCellStyle());
        cell = row.createCell(7);
        cell.setCellValue(shippingOrder.getCopyNum());
        cell.setCellStyle(sheet.getRow(26).getCell(7).getCellStyle());

        row = sheet.getRow(31);
        cell = row.getCell(0);
        cell.setCellValue(shippingOrder.getMarks() + "\r\n" + shippingOrder.getNos());
        cell = row.getCell(3);
        cell.setCellValue(shippingOrder.getDescription());
        cell = row.getCell(5);
        cell.setCellValue(shippingOrder.getQuantity());
        cell = row.getCell(6);
        cell.setCellValue(shippingOrder.getGrossWeights());
        cell = row.getCell(8);
        cell.setCellValue(shippingOrder.getTotalVolume());
        row = sheet.getRow(37);
        cell = row.getCell(1);
        cell.setCellValue(shippingOrder.getSpecialConditio());
        response.setHeader("content-disposition","attachment;filename=shippingOrder.xlsx");
        ServletOutputStream outputStream = response.getOutputStream();
        workbook.write(outputStream);
        outputStream.close();
        workbook.close();
    }

    @RequestMapping("/toPDF")
    @ResponseBody
    public void toPDF(String id) throws Exception {
        ShippingOrder shippingOrder = getShippingOrder(id);
        InputStream in = session.getServletContext().getResourceAsStream("/jasper/shippingOrder.jasper");
        List<ShippingOrder> list = new ArrayList<>();
        list.add(shippingOrder);
        JRDataSource dataSource = new JRBeanCollectionDataSource(list);
        JasperPrint jasperPrint = JasperFillManager.fillReport(in, null, dataSource);
        response.setHeader("content-disposition","attachment;filename=shippingOrder.pdf");
        ServletOutputStream outputStream = response.getOutputStream();
        JasperExportManager.exportReportToPdfStream(jasperPrint,outputStream);
    }

    /*location.href="${ctx}/cargo/shipping/toShipping.do?id="+id;*/
    @RequestMapping("/toShip")
    public String toShipping(String id) {
        Shipping shipping = new Shipping();
        shipping.setShippingOrderId(id);
        Packing packing = packingService.findById(id);
        if (packing.getState() != 0) {
            throw new RuntimeException("该装箱单已生产委托，不能重复委托");
        }
        ExportExample exportExample = new ExportExample();
        exportExample.createCriteria().andIdIn(Arrays.asList(packing.getExportIds().split(",")));
        List<Export> exportList = exportService.findByIds(exportExample);
        shipping.setPortOfLoading(packing.getShipmentPort());
        shipping.setPortOfDischar(packing.getDestinationPort());
        shipping.setNotifyPariy(packing.getConsignee());
        String lcNo = "";
        String marks = "";
        if (exportList != null && exportList.size() > 0) {
            for (Export export : exportList) {
                if (export.getLcno() != null) {
                    lcNo += export.getLcno() + " ";
                }
                if (export.getMarks() != null) {
                    marks += export.getMarks() + " ";
                }
            }
        }
        shipping.setLcNo(lcNo);
        shipping.setMarks(marks);
        request.setAttribute("shipping", shipping);
        return "/cargo/shipping/shipping-toShip";
    }

    public ShippingOrder getShippingOrder(String id){
        Shipping shipping = shippingService.findById(id);
        Packing packing = packingService.findById(id);
        ShippingOrder shippingOrder = ShippingOrder.builder()
                .shipper(shipping.getShipper() != null ? shipping.getShipper() : "")
                .consignee(shipping.getConsignee() != null ? shipping.getConsignee() : "")
                .notifyPariy(shipping.getNotifyPariy())
                .lcNO(shipping.getLcNo() != null ? shipping.getLcNo() : "")
                .portOfLoading(shipping.getPortOfLoading())
                .portOfTrans(shipping.getPortOfTrans() != null ? shipping.getPortOfTrans() : "")
                .portOfDischar(shipping.getPortOfDischar())
                .loadingDate(new SimpleDateFormat("yyyy-MM-dd").format(shipping.getLoadingDate())!=null?
                        new SimpleDateFormat("yyyy-MM-dd").format(shipping.getLoadingDate()):"")
                .limitDate(new SimpleDateFormat("yyyy-MM-dd").format(shipping.getLimitDate())!=null?
                        new SimpleDateFormat("yyyy-MM-dd").format(shipping.getLimitDate()):"")
                .isBatch("1".equals(shipping.getIsBatch())?"是":"否")
                .isTrans("1".equals(shipping.getIsTrans())?"是":"否")
                .copyNum(shipping.getCopyNum() != null ? shipping.getCopyNum() : "")
                .marks(shipping.getMarks() != null ? shipping.getMarks() : "")
                .nos(packing.getExportNos() != null ? packing.getExportNos() : "")
                .description(packing.getDescription() != null ? packing.getDescription() : "")
                .quantity(packing.getNetWeights()+"CTNS")
                .grossWeights(packing.getGrossWeights()+"KGS")
                .totalVolume(packing.getTotalVolume()+"M3")
                .specialConditio(shipping.getSpecialConditio() != null ? shipping.getSpecialConditio() : "")
                .build();
        if (shipping.getState() == 1){
            Invoice invoice = invoiceService.findById(id);
            shippingOrder.setInvoiceId(id);
            shippingOrder.setInvoiceTime(new SimpleDateFormat("yyyy-MM-dd").format(invoice.getInvoiceTime())!=null?
                    new SimpleDateFormat("yyyy-MM-dd").format(invoice.getInvoiceTime()):"");
        } else {
            shippingOrder.setInvoiceId("");
            shippingOrder.setInvoiceTime("");
        }
        return shippingOrder;
    }
}
